package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.project.dao.AirHumidityDataDAO;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.AirHumidityData;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.project.po.entity.Greenhouse;
import edu.ynu.se.xiecheng.achitectureclass.project.po.vo.EnvironmentVO;
import edu.ynu.se.xiecheng.achitectureclass.project.utils.GreenhouseDeviceUtils;
import edu.ynu.se.xiecheng.achitectureclass.project.utils.SensorApiClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AirHumidityDataService extends LogicService<AirHumidityDataDAO, AirHumidityData, Long> {

    @Autowired
    private SensorApiClient sensorApiClient;
    @Autowired
    private GreenhouseDeviceUtils greenhouseDeviceUtils;

    public AirHumidityDataService(AirHumidityDataDAO lr) {
        super(lr);
    }

    /**
     * 从传感器API获取空气温度数据并存储到数据库
     */
    public void fetchAndSaveAirHumidityData() {
        // 示例 Box 编号和传感器 ID 列表
        String boxNo = "300822040454";
        List<String> sensorIds = List.of("327061586065758014");

        // 调用外部接口获取传感器数据
        List<Map<String, Object>> sensorData = sensorApiClient.fetchSensorData(sensorIds, boxNo);

        for (Map<String, Object> data : sensorData) {
            System.out.println("Sensor data: " + data);

            // 创建或更新大棚信息
            String boxId = data.get("boxId").toString(); // 大棚 ID
            Greenhouse greenhouse = greenhouseDeviceUtils.getOrCreateGreenhouse(boxId);

            // 创建或更新设备信息
            String sensorId = data.get("id").toString(); // 传感器设备 ID
            String name = data.get("name").toString();
            Device device = greenhouseDeviceUtils.getOrCreateDevice(sensorId, name, greenhouse);

            //创建空气湿度度数据实例并设置属性
            AirHumidityData airHumidityData = new AirHumidityData();
            airHumidityData.setName(name);
            airHumidityData.setValue(Double.parseDouble(data.get("value").toString())/10.0);
            airHumidityData.setUnit("%RH");
            airHumidityData.setTimestamp(new Date());
            airHumidityData.setDevice(device);
            dao.save(airHumidityData);

        }
    }


    /**
     * 获取当前空气湿度数据
     * @return
     */
    public EnvironmentVO getCurrentAirTemperature() {
        AirHumidityData data = dao.findFirstByOrderByTimestampDesc();
        if (data != null) {
            return new EnvironmentVO(
                    data.getValue(),
                    "°C",
                    data.getTimestamp().toString()
            );
        }
        return new EnvironmentVO(0.0, "°C", null);
    }
}
